package FlashServer;

import java.io.BufferedReader;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.InterruptedIOException;
import java.io.PrintWriter;
import java.net.Socket;

class SocketConnection extends Thread {
	private Socket _socket;
	private BufferedReader _socketIn;
	private PrintWriter _socketOut;

	public SocketConnection(Socket socket_) {
		_socket = socket_;
	}

	public void run() {
		try {
			_socket.setSoTimeout(10000);
			_socketIn = new BufferedReader(new InputStreamReader(_socket.getInputStream()));
			_socketOut = new PrintWriter(_socket.getOutputStream(), true);
		} catch (IOException e) {
			if (MainServer.DEBUG)
				System.out.println("IO Exception " + e.getMessage());
			return;
		}

		readPolicyRequest();
	}

	private void readPolicyRequest() {
		try {
			if (MainServer.POLICY_REQUEST.equals(read())) {
				write(MainServer.PolicyXML());
			}
		} catch (Exception e) {
			if (MainServer.DEBUG)
				System.out.println("Exception " + e.getMessage());
		}
		close();
	}

	private String read() throws IOException, EOFException,
			InterruptedIOException {
		StringBuffer buffer = new StringBuffer();
		int codePoint;
		boolean zeroByteRead = false;

		if (MainServer.DEBUG) {
			System.out.println("Reading...");
		}
		do {
			codePoint = _socketIn.read();
			if (codePoint == 0)
				zeroByteRead = true;
			else
				buffer.appendCodePoint(codePoint);
		} while (!zeroByteRead && buffer.length() < 100);
		if (MainServer.DEBUG)
			System.out.println("Read: " + buffer.toString());

		return buffer.toString();
	}

	public void write(String msg) {
		_socketOut.println(msg + "\u0000");
		_socketOut.flush();
		if (MainServer.DEBUG) {
			System.out.println("Wrote: " + msg);
		}
	}

	public void close() {
		try {
			if (_socket != null)
				_socket.close();
			if (_socketOut != null)
				_socketOut.close();
			if (_socketIn != null)
				_socketIn.close();
			System.out.println("Port close.");
		} catch (IOException e) {
		}

		_socketIn = null;
		_socketOut = null;
		_socket = null;
	}

}